const urlParams = new URL(window.location.href);
var exp_id = urlParams.searchParams.get("exp_id"),
    token = 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiI0NjUyNjY2NjI2MzE5MzYwMDAiLCJleHAiOjE1NzczNTQzMzIsImlhdCI6MTU3NDc2MjMzMiwiaXNzIjoiVGF1cnVzIEZ1dHVyZSJ9.PdoCQ5u4f-lZDLb5poeZInQayo6s7LVASMxCAeejOpRPkvHm_DPBrHzfqGDEEo6VuFZ9YReRhaJfJ6WWknKXZg',
    daren,
    exp,
    store,
    baseUrl = 'https://192.168.1.40:8901/user_service'
var init;
function sendHttp(type, url, data) {
  return new Promise(function(resolve, reject) {
    const ajaxPram = {
      type,
      url: baseUrl + url,
      contentType: "application/x-www-form-urlencoded",
      headers: {
        Authorization: token,
        Lang: 'zh-CN',
        Currency: 'rmb',
        Version: 100,
        // ['User-Agent']: 'ios'
      },
      data,
      dataFilter: function(data,type) {
        return JSON.stringify(jsonlint.parse(data))
      },
      success: function (res) {
        resolve(res)
      },
      error: function(err) {
        reject(err)
      }
    }
    $.ajax(ajaxPram)
  })
}
// 与原生交互
function transferNative(parm) {
  var data = {
        action: "jumpPage", 
        data: parm, 
        callback: function(){}
      };
  window.WebViewJavascriptBridge.callHandler(
       'callNativeToDo', //指定接收参数 callNativeToDo
       data, 
       function(responseData) {}
     );
}
// 喜欢达人操作
function handleFavorite() {
  const sendFavorite = function() {
    const postData = {
      favorite_type: 6,
      business_id: daren.id
    }
    sendHttp("post","/favorite",postData).then(res=>{
      if (res.code === 100200) {
        if (daren.is_follow) {
          $(".favorite").removeClass("cancel-favorite")
          $(".favorite").text("+喜欢")
        } else {
          $(".favorite").addClass("cancel-favorite")
          $(".favorite").text("已喜欢")
        }
        daren.is_follow = !daren.is_follow
      } else {
        showTips(res.msg)
      }
    })
  }
  if (daren.is_follow) {
    showConfirm(' 确认取消喜欢，并退出群聊吗？',function() {
      sendFavorite()
    },function() {
      console.log('取消操作');
    })
  } else {
    sendFavorite()
  }

}
// 进入店铺
function handleEntryStore() {
  alert('handleEntryStore')
}
// 点赞
function handelThumbUp() {
  const postData = {
    biz_type: 4,
    biz_id: exp.id,
    like_type: 1
  }
  sendHttp("post","/like_dislike",postData).then(res=>{
    if (res.code === 100200) {
      const el = $(".thumb-up")
      if (exp.is_liked) {
        el.removeClass('bg-color-active')
      } else {
        el.addClass('bg-color-active')
      }
      exp.is_liked = !exp.is_liked
      init()
    } else {
      showTips(res.msg)
    }
  })
}
// 踩
function handelThumbDown() {
  const postData = {
    biz_type: 4,
    biz_id: exp.id,
    like_type: 2
  }
  sendHttp("post","/like_dislike",postData).then(res=>{
    if (res.code === 100200) {
      const el = $(".thumb-down")
      if (exp.is_liked) {
        el.removeClass('bg-color-active')
      } else {
        el.addClass('bg-color-active')
      }
      exp.is_liked = !exp.is_liked
      init()
    } else {
      showTips(res.msg)
    }
  })
}
// 经验加心
function handleJiaxin() {
  const postData = {
    favorite_type: 4,
    business_id: exp.id
  }
  sendHttp("post","/favorite",postData).then(res=>{
    if (res.code === 100200) {
      if (exp.is_favorite) {
        $(".jiaxin > img").attr("src","img/jiaxin.png")
      } else {
        $(".jiaxin > img").attr("src","img/xin.png")
      }
      daren.is_favorite = !daren.is_favorite
      init()
    } else {
      showTips(res.msg)
    }
  })
}
function handleReport() {
  alert('handleReport')
}
// 进入达人首页
function handleEntryDaren() {

}
$(document).ready(function(){
  const data = {
    img:[
      './img/timg-3.jpg',
      './img/timg-3.jpg',
      './img/timg-3.jpg',
      './img/timg-3.jpg',
      './img/timg-3.jpg',
    ]
  }
  init = function() {
    sendHttp("get","/experience_detail",{exp_id:'465229098701164544'}).then((res)=>{
      if (res.code !== 100200) {
        showTips(res.msg)
        return false;
      }
      daren = res.data.daren;
      exp = res.data.exp;
      store = res.data.store;
      // 渲染达人信息
      $(".user-nickname").text(daren.nickname)
      $(".user-avatar > img").attr("src",daren.avatar_url)
      $(".user-label").text(daren.label)
      // 渲染喜欢信息
      if (daren.is_follow) {
        $(".favorite").addClass("cancel-favorite")
        $(".favorite").text("已喜欢")
      }
      // 渲染经验
      $(".content-text").text(exp.content)
      // 渲染配图
      let figures = ''
      exp.image.forEach(i=>{
        figures += `<figure> <img src=${i}> </figure>`
      })
      $(".my-gallery").addClass(`item-${exp.image.length}`)
      $(".my-gallery").html(figures)
      // 渲染经验底部数据
      $(".time").text(formatTime(exp.create_time))
      $(".thumb-up-num").text(exp.like_count)
      $(".jiaxin-num").text(exp.favorite_count)
      // 渲染赞同/踩
      if (exp.is_liked) {
        $(".thumb-up").addClass('bg-color-active')
      } else {
        $(".thumb-up").reomveClass('bg-color-active')
      }
      if (exp.is_disliked) {
        $(".thumb-down").addClass('bg-color-active')
      } else {
        $(".thumb-down").removeClass('bg-color-active')
      }
      // 渲染加心
      if (exp.is_favorite) {
        $(".jiaxin > img").attr("src","img/xin.png")
      }
      // 渲染店铺信息
      $(".store-name").text(store.name)
      $(".store-per-consume").text(`人均:$${store.per_consume}`)
      $(".store-address").text(store.address)
    })
  }
  function initPhoto() {
    let figures = ''
    data.img.forEach(i=>{
      figures += `<figure> <img src=${i}> </figure>`
    })
    $(".my-gallery").addClass(`item-${data.img.length}`)
    $(".my-gallery").html(figures)
  }
  initPhoto()
});
function showTips(msg) {
  if (msg) {
    $("#tips").text(msg);
  }
  $("#tips").show();
  setTimeout(function() {
    $("#tips").hide();
  }, 2000);
}
// 显示confirm
function showConfirm(msg,confirm,cancel) {
  $("#confirm > .confirm-body").html(`<span>${msg}</span>`)
  $(".confirm-confirm").unbind("click").click(function() {
    confirm()
     $("#confirm").hide()
  })
  $(".confirm-cancel").unbind("click").click(function() {
    cancel()
    $("#confirm").hide()
  })
  $("#confirm").show()
}
// 格式化时间戳
function formatTime(timestamp) {
  const t = new Date(timestamp*1000);
  const Y = t.getFullYear();
  const M = (t.getMonth() + 1) < 10 ? `0${t.getMonth() + 1}` : (t.getMonth() + 1);
  const D = t.getDate() < 10 ? `0${t.getDate()}` : t.getDate();
  const H = t.getHours() < 10 ? `0${t.getHours()}` : t.getHours();
  const I = t.getMinutes() < 10 ? `0${t.getMinutes()}` : t.getMinutes();
  const S = t.getSeconds() < 10 ? `0${t.getSeconds()}` : t.getSeconds();
  return `${Y}-${M}-${D} ${H}:${I}:${S}`
}

// 初始化图片预览
var initPhotoSwipeFromDOM = function(gallerySelector) {
  var parseThumbnailElements = function(el) {
    var thumbElements = el.childNodes,
      numNodes = thumbElements.length,
      items = [],
      figureEl,
      linkEl,
      size,
      item;
    for (var i = 0; i < numNodes; i++) {
      figureEl = thumbElements[i]; // <figure> element
      if (figureEl.nodeType !== 1) {
        continue;
      }
      linkEl = figureEl.children[0]; // <img> element
      item = {
        src: linkEl.getAttribute('src'),
        w: linkEl.naturalWidth,
        h: linkEl.naturalHeight
      };
      // 预加载缩略图
      item.msrc = linkEl.getAttribute('src');
      item.el = figureEl; // save link to element for getThumbBoundsFn
      items.push(item);
    }
    return items;
  };
  var closest = function closest(el, fn) {
    return el && (fn(el) ? el : closest(el.parentNode, fn));
  };
  var onThumbnailsClick = function(e) {
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;
    var eTarget = e.target || e.srcElement;
    var clickedListItem = closest(eTarget, function(el) {
      return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
    });
    if (!clickedListItem) {
      return;
    }
    var clickedGallery = clickedListItem.parentNode,
      childNodes = clickedListItem.parentNode.childNodes,
      numChildNodes = childNodes.length,
      nodeIndex = 0,
      index;
    for (var i = 0; i < numChildNodes; i++) {
      if (childNodes[i].nodeType !== 1) {
        continue;
      }
      if (childNodes[i] === clickedListItem) {
        index = nodeIndex;
        break;
      }
      nodeIndex++;
    }
    if (index >= 0) {
      openPhotoSwipe(index, clickedGallery);
    }
    return false;
  };
  var photoswipeParseHash = function() {
    var hash = window.location.hash.substring(1),
      params = {};
    if (hash.length < 5) {
      return params;
    }
    var vars = hash.split('&');
    for (var i = 0; i < vars.length; i++) {
      if (!vars[i]) {
        continue;
      }
      var pair = vars[i].split('=');
      if (pair.length < 2) {
        continue;
      }
      params[pair[0]] = pair[1];
    }
    if (params.gid) {
      params.gid = parseInt(params.gid, 10);
    }
    return params;
  };
  var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
    var pswpElement = document.querySelectorAll('.pswp')[0],
      gallery,
      options,
      items;

    items = parseThumbnailElements(galleryElement);
    options = {
      tapToClose:true, // 点击关闭
      galleryUID: galleryElement.getAttribute('data-pswp-uid'),
      getThumbBoundsFn: function(index) {
        // See Options -> getThumbBoundsFn section of documentation for more info
        var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
          pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
          rect = thumbnail.getBoundingClientRect();
        return {
          x: rect.left,
          y: rect.top + pageYScroll,
          w: rect.width
        };
      },
    };
    if (fromURL) {
      if (options.galleryPIDs) {
        for (var j = 0; j < items.length; j++) {
          if (items[j].pid == index) {
            options.index = j;
            break;
          }
        }
      } else {
        options.index = parseInt(index, 10) - 1;
      }
    } else {
      options.index = parseInt(index, 10);
    }
    if (isNaN(options.index)) {
      return;
    }
    if (disableAnimation) {
      options.showAnimationDuration = 0;
    }
    options.showHideOpacity  = true
    gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
  };
  var galleryElements = document.querySelectorAll(gallerySelector);
  for (var i = 0, l = galleryElements.length; i < l; i++) {
    galleryElements[i].setAttribute('data-pswp-uid', i + 1);
    galleryElements[i].onclick = onThumbnailsClick;
  }
  var hashData = photoswipeParseHash();
  if (hashData.pid && hashData.gid) {
    openPhotoSwipe(hashData.pid, galleryElements[hashData.gid - 1], true, true);
  }
};
  initPhotoSwipeFromDOM('.my-gallery');